import { getBusinessTypeList, getProjectManagerMemberListResult, getProjectRoleInformation, getIslandSpaceList, getProjectIslandMaterial, deleteProjectIslandMaterial } from '../../../../../api/index'
import { formatTimeTwo } from '../../../../../utils/util'

Component({
  properties: {
    detail: {
      type: Object,
      value: {}
    },
    roleIds: {
      type: Array,
      value: []
    },
    timestamp: {
      type: Number,
      value: 0
    }
  },
  observers: {
    'timestamp' (val) {
      if (val) this.getBusiness()
    }
  },
  data: {
    business: [],
    activeBusiness: '',
    businessTitle: '',
    memberBusiness: '',
    materialBusiness: '',
    paperBusiness: '',
    roleInformation: {},
    memberList: [],
    activeMember: '',
    myselfMember: {},
    memberTitle: '全部成员',
    spaceList: [],
    activeSpace: '',
    allCount: 0,
    materialList: [],
    spaceTabH: 0,
    sections: [],
    refresher: false,
    currentMember: {}
  },
  methods: {
    async onRefresh () {
      await this.getProjectRoleInformation()
      this.setData({ refresher: false })
    },
    edit ({ currentTarget: { dataset: { item } } }) {
      wx.$nav.navigateTo(`/pages/account/project/editMaterial/index?projectId=${this.data.detail.project_id}&businessType=${this.data.activeBusiness}&businessTypeTxt=${this.data.businessTitle}&id=${item.selectId}&type=islandProject`)
    },
    async delMaterial () {
      try {
        if (!this.data.sections.length) {
          wx.showToast({ title: '请先选择要删除的数据！', icon: 'none' })
          return
        }
        const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除选择的选材吗？' })
        if (confirm) {
          let ids = this.data.sections.map(item => { return item.selectId })
          await deleteProjectIslandMaterial({ projectId: this.data.detail.project_id, projectSelectIds: ids.join(','), roleIds: this.data.roleIds })
          this.setData({ sections: [] })
          wx.showToast({ title: '删除成功！', icon: 'none' })
          this.getSpaceList()
        }
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    generateBook () {
      if (!this.data.sections.length) {
        wx.showToast({ title: '请先选择材料！', icon: 'none' })
        return
      }
      let ids = this.data.sections.map(item => { return item.selectId })
      wx.$nav.navigateTo(`/pages/account/project/books/index?ids=${ids.join(',')}&projectId=${this.data.detail.project_id}&type=islandProject&businessType=${this.data.activeBusiness}&city=${this.data.detail.city}&roleIds=${this.data.roleIds}`)
    },
    selectMember ({ currentTarget: { dataset: { item } } }) {
      this.selectComponent('#member').toggle()
      this.setData({ activeMember: item.userId, memberTitle: item.userName, activeSpace: '', currentMember: item })
      this.getMaterialList()
      this.getSpaceList()
    },
    selectBusiness ({ currentTarget: { dataset: { item } } }) {
      this.selectComponent('#business').toggle()
      this.setData({ activeBusiness: item.id, businessTitle: item.title, activeSpace: '' })
      this.getMemberList()
      this.getSpaceList()
    },
    addSpace () {
      wx.$nav.navigateTo(`/pages/account/island/spaceManage/index?id=${this.data.detail.project_id}`)
    },
    selectRadio ({ currentTarget: { dataset: { item, index } } }) {
      let key = `materialList[${index}].isChecked`
      this.setData({ [key]: !item.isChecked })
      let sections = this.data.materialList.filter(item => item.isChecked)
      this.setData({ sections: sections })
    },
    cancelAll () {
      this.data.materialList.forEach(item => {
        item.isChecked = false
      })
      this.setData({ materialList: this.data.materialList, sections: [] })
    },
    selectSpace ({ currentTarget: { dataset: { item } } }) {
      this.setData({ activeSpace: item && item.spaceId ? item.spaceId : '' })
      this.getMaterialList()
    },
    setBusiness () {
      let business = this.data.detail.business_type.split(',')
      let newBusiness = []
      this.data.businessList.forEach(item => {
        business.forEach(row => {
          if (item.id === parseInt(row)) newBusiness.push(item)
        })
      })
      this.setData({
        business: newBusiness,
        activeBusiness: newBusiness[0].id,
        businessTitle: newBusiness[0].title,
        memberBusiness: newBusiness[0].id,
        materialBusiness: newBusiness[0].id,
        paperBusiness: newBusiness[0].id
      })
    },
    async getBusiness () {
      try {
        const { ResultSet } = await getBusinessTypeList()
        this.setData({ businessList: ResultSet.userData.businessList.value })
        this.setBusiness()
        this.getProjectRoleInformation()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getMemberList () {
      try {
        const { ResultSet } = await getProjectManagerMemberListResult({ project_id: this.data.detail.project_id, business_type: this.data.activeBusiness, isMaterialManager: this.data.roleInformation.materialManager })
        let activeItem = ResultSet.userData.memberList[0]
        this.data.activeMember = activeItem.userId
        this.data.memberTitle = activeItem.userName
        this.setData({ memberList: ResultSet.userData.memberList, activeMember: this.data.activeMember, memberTitle: this.data.memberTitle, currentMember: activeItem })
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getProjectRoleInformation () {
      try {
        const { ResultSet } = await getProjectRoleInformation({ projectId: this.data.detail.project_id, roleIds: this.data.roleIds, businessType: this.data.activeBusiness })
        this.setData({ roleInformation: ResultSet.userData })
        await this.getMemberList()
        this.getSpaceList()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getSpaceList () {
      try {
        let query = {
          projectId: this.data.detail.project_id,
          businessType: this.data.activeBusiness,
          businessTypeText: this.data.businessTitle,
          type: 1
        }
        if (this.data.activeMember) query.userId = this.data.activeMember
        const { ResultSet } = await getIslandSpaceList({ ...query })
        let allCount = 0
        if (ResultSet.userData.result.length) allCount = ResultSet.userData.result.map(item => { return item.count }).reduce((n,m) => n + m)
        this.setData({ spaceList: ResultSet.userData.result, allCount: allCount })
        this.getMaterialList()
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    },
    async getMaterialList () {
      try {
        let query = {
          projectId: this.data.detail.project_id,
          businessType: this.data.activeBusiness
        }
        if (this.data.activeSpace) query.spaceId = this.data.activeSpace
        if (this.data.activeMember) query.userId = this.data.activeMember
        const { ResultSet } = await getProjectIslandMaterial({ ...query })
        ResultSet.userData.data.forEach(item => { return item.isChecked = false })
        this.setData({ materialList: ResultSet.userData.data })
      } catch (err) {
        console.log(err)
        wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
      }
    }
  }
})